from flask import Flask, render_template, request, redirect, url_for
import pymysql

app = Flask(__name__,template_folder='')


# 配置数据库连接
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'diary_db'

def get_db_connection():
    connection = pymysql.connect(
        host=app.config['MYSQL_HOST'],
        user=app.config['MYSQL_USER'],
        password=app.config['MYSQL_PASSWORD'],
        db=app.config['MYSQL_DB'],
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
    date = request.form['date']
    weather = request.form['weather']
    mood = request.form['mood']
    event = request.form['event']

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diary_entries (date, weather, mood, event) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, event))
        connection.commit()
    finally:
        connection.close()

    return redirect(url_for('history'))

@app.route('/history')
def history():
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM diary_entries ORDER BY date DESC"
            cursor.execute(sql)
            entries = cursor.fetchall()
        return render_template('history.html', entries=entries)
    finally:
        connection.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)